<?php
class ReserveModel extends CI_Model{
    public function __construct(){
        $this->load->database();
        parent:: __construct();
    }

    public function get($seatId, $shiftId){
        $data = array(
            'seatId'=>$seatId,
            'shiftId'=>$shiftId,
            'cancelTime'=> null
        );
        $query = $this->db->get_where("reservationlist", $data,1);
        return  $query->num_rows();
    }
    
    //get reservation list  by condition
    public function getList(){
        $where = array(
            'cancelTime'=>null,
        ); 

        $query = $this->db->get_where("reservationlist", $where,10);
        return $query->result_array();

    }
    
    public function getSeat($userId, $shiftId){
        $where= array(
            'operationTime <>'=>null,
            'shiftId'=>$shiftId
            );
        $this->db->select('seatId');
        $query = $this->db->get_where("reservationlist", $where,100);
        $seatIds = $query->result_array();
        $seatIds = array_values($seatIds);
        $i=1;
        while(in_array($i, $seatIds) && $i<=60){
            $i++;
        }
        
        if($i>60){
            $code =-1;
        }else{
            $code =0;
        }
        
        return array('code'=>$code,"seatNum"=>$i);
    }


    public function add($userId, $seatId, $shiftId, $operationTime, $formId){
        $data= array(
            'userId'=>$userId, 
            'seatId'=>$seatId,
            'shiftId'=>$shiftId,
            'operationTime'=>$operationTime,
            'formId'=>$formId
        );
        $this->db->insert('reservationlist', $data); 

        return $this->db->affected_rows();
    }

    public function checkCancel($userId, $shiftId){
        $data = array(
            'shiftId'=>$shiftId,
            'cancelTime' =>null,
            'userId'=>$userId,
        );
        $query = $this->db->get_where("reservationlist", $data,1);
        return  $query->num_rows();
    }

    public function checkReserved($userId, $shiftId){
        return $this->checkCancel($userId, $shiftId);
    }


    public function cancel($userId, $shiftId, $cancelTime){
        
        $data= array(
            'userId'=>$userId, 
            'shiftId'=>$shiftId,
            'cancelTime'=>null
        );
        $query= $this->db->get_where("reservationlist", $data);
        $result= $query->result_array();
        if(isset($result[0])){
            $where = array('reservationId'=>$result[0]['reservationId']);
            $query = $this->db->update("reservationlist", array('cancelTime'=>$cancelTime), $where);
        }else{
            $query = true;
        }

        return  $query;
    }

    public function getStatus(){

    }


    public function updateViolaiton(){

    }

}
